package com.czy.owner.ui.physicalorder;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.adapter.ConfirmOrderAdapter2;
import com.czy.owner.api.CollectFreightApi;
import com.czy.owner.api.GetUserOrderCouponsApi;
import com.czy.owner.api.SelectStoreApi;
import com.czy.owner.api.SubmitOrderApi;
import com.czy.owner.api.UserLocationApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.CommitOrderModel;
import com.czy.owner.entity.GoodsCouponEntity;
import com.czy.owner.entity.GoodsEntity;
import com.czy.owner.entity.OrderSourceEntity;
import com.czy.owner.entity.SelectStoreModel;
import com.czy.owner.entity.UserLocationModel;
import com.czy.owner.entity.UserOrderCoupon;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.address.AddReceiverAddress;
import com.czy.owner.ui.order.OrderActivity;
import com.czy.owner.ui.order.OrderPaidActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2017-05-23
 */

public class ConfirmOrderActivity extends BaseActivity {
    /*列表头部控件*/
    @BindView(R.id.tv_home_delivery_none)
    TextView tvHomeDeliveryNone;
    @BindView(R.id.tv_home_delivery_name)
    TextView tvHomeDeliveryName;
    @BindView(R.id.tv_home_delivery_telephone)
    TextView tvHomeDeliveryTelephone;
    @BindView(R.id.tv_home_delivery_address)
    TextView tvHomeDeliveryAddress;

    @BindView(R.id.rl_home_delivery_wrapper)
    RelativeLayout rlHomeDeliveryWrapper;
    @BindView(R.id.rl_home_delivery_content)
    RelativeLayout rlHomeDeliveryContent;

    @BindView(R.id.ll_store_delivery_wrapper)
    LinearLayout llStoreDeliveryWrapper;


    @BindView(R.id.tv_store_delivery_none)
    TextView tvStoreDeliveryNone;
    @BindView(R.id.tv_store_delivery_name)
    TextView tvStoreDeliveryName;
    @BindView(R.id.tv_store_delivery_telephone)
    TextView tvStoreDeliveryTelephone;
    @BindView(R.id.tv_store_delivery_distance)
    TextView tvStoreDeliveryDistance;
    @BindView(R.id.tv_store_delivery_address)
    TextView tvStoreDeliveryAddress;


    //    wyang新增
    @BindView(R.id.ll_store)
    LinearLayout llStore;
    @BindView(R.id.ll_system)
    LinearLayout llSystem;
    @BindView(R.id.ll_transfer)
    LinearLayout llTransfer;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_system_name)
    TextView tvSystemName;
    @BindView(R.id.tv_transfer_name)
    TextView tvTransferName;


    //    底部控件  store
    @BindView(R.id.tv_coupon1)
    TextView tvCoupon1;
    @BindView(R.id.tv_goods_freight1)
    TextView tvGoodsFreight1;
    @BindView(R.id.tv_goods_discount1)
    TextView tvGoodsDiscount1;
    @BindView(R.id.tv_goods_small_total1)
    TextView tvGoodsSmallTotal1;
    @BindView(R.id.ll_store_member_price)
    LinearLayout llStoreMemberPrice;
    @BindView(R.id.tv_goods_member_discount)
    TextView tvGoodsMemberDiscount;

    //底部控件system
    @BindView(R.id.tv_coupon2)
    TextView tvCoupon2;
    @BindView(R.id.tv_goods_freight2)
    TextView tvGoodsFreight2;
    @BindView(R.id.tv_goods_discount2)
    TextView tvGoodsDiscount2;
    @BindView(R.id.tv_goods_small_total2)
    TextView tvGoodsSmallTotal2;


    //底部控件transfer
    @BindView(R.id.tv_coupon3)
    TextView tvCoupon3;
    @BindView(R.id.tv_goods_freight3)
    TextView tvGoodsFreight3;
    @BindView(R.id.tv_goods_discount3)
    TextView tvGoodsDiscount3;
    @BindView(R.id.tv_goods_small_total3)
    TextView tvGoodsSmallTotal3;


    @BindView(R.id.rv_confirm_order_store)
    EasyRecyclerView rvConfirmOrderStore;
    @BindView(R.id.rv_confirm_order_system)
    EasyRecyclerView rvConfirmOrderSystem;
    @BindView(R.id.rv_confirm_order_transfer)
    EasyRecyclerView rvConfirmOrderTransfer;
    @BindView(R.id.et_goods_note)
    EditText etGoodsNote;
    @BindView(R.id.tv_pay_amount)
    TextView tvPayAmount;
    @BindView(R.id.tv_submit_order)
    TextView tvSubmitOrder;

    public static final int PICK_ADDRESS_HOME = 0X91;
    public static final int PICK_ADDRESS_STORE = 0X92;
    public static final int ADD_ADDRESS = 0X93;

    public static final int PICK_COUPON = 0X96;
    public static final int PICK_COUPON2 = 0X97;
    public static final int PICK_COUPON3 = 0X98;


    private ConfirmOrderAdapter2 mAdapterStoreAdapter;
    private ConfirmOrderAdapter2 mAdapterSystemAdapter;
    private ConfirmOrderAdapter2 mAdapterTransferAdapter;
    private List<GoodsEntity> goodsList;
    private ConfirmOrderJumpType confirmOrderJumpType = ConfirmOrderJumpType.CART;
    private double sumStoreGoodsPrice, sumStoreGoodsCouponsPrice2, sumSystemGoodsPrice, sumTransferGoodsPrice, sumStoreServicePrice, sumSystemServicePrice, sumTransferServicePrice,
            sumStoreCarriagePrice, sumSystemCarriagePrice, sumTransferCarriagePrice, sumStoreDiscount, sumSystemDiscount, sumTransferDiscount,
            settlementStorePrice, settlementSystemPrice, settlementTransferPrice, sumMemberPrice, sumMemberDiscount;
    private HashMap<Integer, Double> carriagePriceMap = new HashMap<>();
    private List<Integer> carriagePriceIndex = new ArrayList<>();
    private boolean hasGetCarriagePrice = false;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private double longItude;
    private double latItude;

    private String installGoodIds = "";
    private GoodsEntity tmpGoodsEntity;
    private UserLocationModel.ListBean tmpUserLocation;
    private SelectStoreModel tmpSelectStore;
    private GoodsCouponEntity tmpStoreGoodsCoupon;
    private GoodsCouponEntity tmpSystemGoodsCoupon;
    private GoodsCouponEntity tmpTransferGoodsCoupon;
    private int sumStoreEnabledCoupon = 0, sumSystemEnabledCoupon, sumTransferEnabledCoupon;
    private CarInfo mCarInfo;
    public static final String TRANSMISSION_GOODS_TYPE_KEY = "goods_type_key";
    public static final String TRANSMISSION_CAR_INFO = "car_info_key";
    private String isShoppingCar = "2"; //2  商品详情  1 购物车

    public enum ConfirmOrderJumpType {
        WORK,               // 项目保养跳转过来的
        CART                // 购物车
    }


    private boolean needInstall = false, installStoreAllSame = true;

    //  2017-11-02 wangyang
    private int receiveStoreId = 0;
    private List<GoodsEntity> storeList = new ArrayList();
    private List<GoodsEntity> systemList = new ArrayList<>();
    private List<GoodsEntity> transfermList = new ArrayList<>();
    private List<OrderSourceEntity> orderSourceEntityList = new ArrayList<>();
    private boolean isSecKill = false;

    private double toTransferStorePrice = 0.00;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_confirm_order;
    }

    @Override
    protected void initInjector() {
        getToolbarTitle().setText("订单确认");
        isSecKill = getIntent().getBooleanExtra("isSecKill", false);
        MyLog.e("yang", "isSecKill==" + isSecKill);
        if (getIntent().getExtras() == null || (goodsList = (List<GoodsEntity>) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(this, "参数异常!");
            finish();
            return;
        }
        isShoppingCar = getIntent().getStringExtra("isShoppingCar");

        for (int i = 0; i < goodsList.size(); i++) {
            MyLog.e("yang", "type===" + goodsList.get(i).getBelongsType());
            if (goodsList.get(i).getBelongsType().equals("store")) {
                storeList.add(goodsList.get(i));
            } else if (goodsList.get(i).getBelongsType().equals("system")) {
                systemList.add(goodsList.get(i));

                if(!TextUtils.isEmpty(isShoppingCar)){
                    if (isShoppingCar.equals("1")) {
                        for (int j = 0; j < goodsList.get(i).getItemFromList().size(); j++) {
                            OrderSourceEntity orderSourceEntity = new OrderSourceEntity();
                            if(!TextUtils.isEmpty(goodsList.get(i).getItemFromList().get(j).getFromType())){
                                orderSourceEntity.setFromType(goodsList.get(i).getItemFromList().get(j).getFromType());
                                orderSourceEntity.setFromTypeId(goodsList.get(i).getItemFromList().get(j).getFromTypeId());
                                orderSourceEntity.setGoodsId(goodsList.get(i).getGoodsId() + "");
                                orderSourceEntity.setSpecGroupKey(goodsList.get(i).getSpecGroupKey());
                                orderSourceEntityList.add(orderSourceEntity);
                            }

                        }
                    } else if (isShoppingCar.equals("2")) {
                        OrderSourceEntity orderSourceEntity = new OrderSourceEntity();
                        if(!TextUtils.isEmpty(goodsList.get(i).getFromType())){
                            orderSourceEntity.setFromType(goodsList.get(i).getFromType());
                            orderSourceEntity.setFromTypeId(goodsList.get(i).getFromTypeId());
                            orderSourceEntity.setGoodsId(goodsList.get(i).getGoodsId() + "");
                            orderSourceEntity.setSpecGroupKey(goodsList.get(i).getSpecGroupKey());
                            orderSourceEntityList.add(orderSourceEntity);
                        }

                    }

                }

            } else {
                transfermList.add(goodsList.get(i));
            }

        }

        MyLog.e("yang", "orderSourceEntityList===" + new Gson().toJson(orderSourceEntityList));


        if (storeList != null && storeList.size() > 0) {
            for (int i = 0; i < storeList.size(); i++) {
                sumStoreGoodsCouponsPrice2 += storeList.get(i).getGoodsSpecValuesPrice() * storeList.get(i).getCount();
                if (storeList.get(i).isHaveMemberPriceFlag() && !storeList.get(i).isSecKill()) {
                    llStoreMemberPrice.setVisibility(View.VISIBLE);
                    //   门店会员价
                    sumMemberPrice += storeList.get(i).getStoreMemberPrice() * storeList.get(i).getCount();
                    //  会员优惠 = 原价 - 门店会员价
                    sumMemberDiscount += (storeList.get(i).getGoodsSpecValuesPrice() * storeList.get(i).getCount() - storeList.get(i).getStoreMemberPrice() * storeList.get(i).getCount());
                    sumStoreGoodsPrice += storeList.get(i).getStoreMemberPrice() * storeList.get(i).getCount();
                } else {
                    sumStoreGoodsPrice += storeList.get(i).getGoodsSpecValuesPrice() * storeList.get(i).getCount();
                }
                if (storeList.get(i).isNeedInstall()) {
                    sumStoreServicePrice += storeList.get(i).getServicePrice() * storeList.get(i).getCount();
                }
            }
        }

        //会员优惠
        tvGoodsMemberDiscount.setText("-￥" + String.format("%.2f", sumMemberDiscount));


        if (systemList != null && systemList.size() > 0) {
            for (int i = 0; i < systemList.size(); i++) {
                sumSystemGoodsPrice += systemList.get(i).getGoodsSpecValuesPrice() * systemList.get(i).getCount();
                if (systemList.get(i).isNeedInstall()) {
                    sumSystemServicePrice += systemList.get(i).getServicePrice() * systemList.get(i).getCount();
                }

            }
        }


        if (transfermList != null && transfermList.size() > 0) {
            for (int i = 0; i < transfermList.size(); i++) {
                sumTransferGoodsPrice += transfermList.get(i).getGoodsSpecValuesPrice() * transfermList.get(i).getCount();
                toTransferStorePrice += transfermList.get(i).getToStorePrice() * transfermList.get(i).getCount();
                MyLog.e("yang", "sumTransferGoodsPrice==" + sumTransferGoodsPrice + "...toTransferStorePrice==" + toTransferStorePrice);
                if (transfermList.get(i).isNeedInstall()) {
                    sumTransferServicePrice += transfermList.get(i).getServicePrice() * transfermList.get(i).getCount();
                }
            }
        }

        confirmOrderJumpType = (ConfirmOrderJumpType) getIntent().getSerializableExtra(TRANSMISSION_GOODS_TYPE_KEY);
        if (confirmOrderJumpType == ConfirmOrderJumpType.WORK && getIntent().getExtras().containsKey(TRANSMISSION_CAR_INFO)) {
            mCarInfo = (CarInfo) getIntent().getSerializableExtra(TRANSMISSION_CAR_INFO);
        }
    }

    @Override
    protected void initViews() {
        if (storeList != null && storeList.size() > 0) {
            llStore.setVisibility(View.VISIBLE);
            mAdapterStoreAdapter = new ConfirmOrderAdapter2(this);
            rvConfirmOrderStore.setLayoutManager(new LinearLayoutManager(this));
            rvConfirmOrderStore.setAdapterWithProgress(mAdapterStoreAdapter);
            mAdapterStoreAdapter.addAll(storeList);
            tvStoreName.setText(UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getStoreName());
        } else {
            llStore.setVisibility(View.GONE);
        }


        if (systemList != null && systemList.size() > 0) {
            llSystem.setVisibility(View.VISIBLE);
            mAdapterSystemAdapter = new ConfirmOrderAdapter2(this);
            rvConfirmOrderSystem.setLayoutManager(new LinearLayoutManager(this));
            rvConfirmOrderSystem.setAdapterWithProgress(mAdapterSystemAdapter);
            mAdapterSystemAdapter.addAll(systemList);
            tvSystemName.setText("平台自营");
        } else {
            llSystem.setVisibility(View.GONE);
        }


        if (transfermList != null && transfermList.size() > 0) {
            llTransfer.setVisibility(View.VISIBLE);
            mAdapterTransferAdapter = new ConfirmOrderAdapter2(this);
            rvConfirmOrderTransfer.setLayoutManager(new LinearLayoutManager(this));
            rvConfirmOrderTransfer.setAdapterWithProgress(mAdapterTransferAdapter);
            mAdapterTransferAdapter.addAll(transfermList);
            tvTransferName.setText("平台转移");
        } else {
            llTransfer.setVisibility(View.GONE);
        }

        switch (confirmOrderJumpType) {
            case WORK:
                needInstall = true;
                installStoreAllSame = true;
                for (int i = 0; i < goodsList.size(); i++) {
                    installGoodIds += (TextUtils.isEmpty(installGoodIds) ? "" : ",") + goodsList.get(i).getGoodsId();
                }
                MyLog.e("yang", "WORK......installGoodIds===" + installGoodIds);
                break;
            case CART:
                int tmpStoreId = 0;
                for (int i = 0; i < goodsList.size(); i++) {
                    if (goodsList.get(i).isNeedInstall()) {
                        needInstall = true;
                        if (tmpStoreId != 0 && tmpStoreId != goodsList.get(i).getServiceInstallStoreId()) {
                            installStoreAllSame = false;
                            //break;
                        }
                        tmpStoreId = goodsList.get(i).getServiceInstallStoreId();
                        tmpGoodsEntity = goodsList.get(i);
                        installGoodIds += (TextUtils.isEmpty(installGoodIds) ? "" : ",") + goodsList.get(i).getGoodsId();
                        MyLog.e("yang", "//////////goodsList.get(i).getGoodsId()===" + goodsList.get(i).getGoodsId());
                    } else {
                        installGoodIds += (TextUtils.isEmpty(installGoodIds) ? "" : ",") + goodsList.get(i).getGoodsId();
                        MyLog.e("yang", "***********" + goodsList.get(i).getGoodsId());
                    }

//                    else if (UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) {
//                        installGoodIds += (TextUtils.isEmpty(installGoodIds) ? "" : ",") + goodsList.get(i).getGoodsId();
//                        MyLog.e("yang","***********"+ goodsList.get(i).getGoodsId());
//                    }

                }
                break;
        }
        if ((needInstall && installStoreAllSame) || UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) {
            initLoc();
        } else {
            getUserAddress();
        }
        calculatePickedGoods();


        //秒杀商品不使用优惠券
        if (!isSecKill) {
            getUserCoupons();
        }


        tvSubmitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isInstall = false;
                for (int i = 0; i < goodsList.size(); i++) {
                    if (goodsList.get(i).isNeedInstall()) {
                        isInstall = true;
                        break;
                    }
                }

                if (UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() == 0) {
                    if (TextUtils.isEmpty(tmpUserLocation.getDetailLocation())) {
                        if (!isInstall) {
                            PhoneUtils.ShowToastMessage(ConfirmOrderActivity.this, "收货信息不完善,请完善后提交");
                        } else {
                            submitOrder();
                        }
                    } else {
                        submitOrder();
                    }
                } else {
                    submitOrder();
                }
            }
        });

    }

    @Override
    protected void updateViews() {

    }

    //    计算商品价格
    private void calculatePickedGoods() {
        double mSystemPrice = 0;
        double mSystemPrice2 = 0;
        double mTransferPrice = 0;
        double mTransferPrice2 = 0;
        double mStorePrice = 0;
        double mStorePrice2 = 0;
        settlementStorePrice = 0;
        settlementSystemPrice = 0;
        settlementTransferPrice = 0;
        tvSubmitOrder.setEnabled(false);


        if (sumStoreCarriagePrice > 0) {
            tvGoodsFreight1.setText("+￥" + String.format("%.2f", sumStoreCarriagePrice));
        } else {
            tvGoodsFreight1.setText("+￥0.00");
        }
        if (sumSystemCarriagePrice > 0) {
            tvGoodsFreight2.setText("+￥" + String.format("%.2f", sumSystemCarriagePrice));
        } else {
            tvGoodsFreight2.setText("+￥0.00");
        }
        if (sumTransferCarriagePrice > 0) {
            tvGoodsFreight3.setText("+￥" + String.format("%.2f", sumTransferCarriagePrice));
        } else {
            tvGoodsFreight3.setText("+￥0.00");
        }


        if (sumStoreServicePrice < 0) {
            sumStoreServicePrice = 0.00;
        }

        if (sumStoreCarriagePrice < 0) {
            sumStoreCarriagePrice = 0.00;
        }
        if (sumSystemServicePrice < 0) {
            sumSystemServicePrice = 0.00;
        }

        if (sumSystemCarriagePrice < 0) {
            sumSystemCarriagePrice = 0.00;
        }


        if (sumTransferServicePrice < 0) {
            sumTransferServicePrice = 0.00;
        }

        if (sumTransferCarriagePrice < 0) {
            sumTransferCarriagePrice = 0.00;
        }


//        门店优惠券结算
        List<GoodsEntity> mStoreList = new ArrayList<>();
        List<GoodsEntity> mStoreList2 = new ArrayList<>();
        if (tmpStoreGoodsCoupon != null) {
            for (int i = 0; i < storeList.size(); i++) {
                if (!TextUtils.isEmpty(tmpStoreGoodsCoupon.getGoodsId())) {
                    if (tmpStoreGoodsCoupon.getUseType().equals("all") || tmpStoreGoodsCoupon.getGoodsId().contains(storeList.get(i).getGoodsId() + "")) {
                        mStoreList.add(storeList.get(i));
                    } else {
                        mStoreList2.add(storeList.get(i));
                    }
                } else {
                    if (tmpStoreGoodsCoupon.getUseType().equals("all")) {
                        mStoreList.add(storeList.get(i));
                    } else if (tmpStoreGoodsCoupon.getUseType().equals("only")) {
                        mStoreList.add(storeList.get(i));
                    } else {
                        mStoreList2.add(storeList.get(i));
                    }
                }


            }

            if (mStoreList != null && mStoreList.size() > 0) {
                for (int i = 0; i < mStoreList.size(); i++) {
                    if (mStoreList.get(i).isHaveMemberPriceFlag() && !mStoreList.get(i).isSecKill()) {
                        mStorePrice += mStoreList.get(i).getStoreMemberPrice() * mStoreList.get(i).getCount();
                    } else {
                        mStorePrice += mStoreList.get(i).getGoodsSpecValuesPrice() * mStoreList.get(i).getCount();
                    }
                }
            }


            if (mStoreList2 != null && mStoreList2.size() > 0) {
                for (int i = 0; i < mStoreList2.size(); i++) {
                    if (mStoreList2.get(i).isHaveMemberPriceFlag() && !mStoreList2.get(i).isSecKill()) {
                        mStorePrice2 += mStoreList2.get(i).getStoreMemberPrice() * mStoreList2.get(i).getCount();
                    } else {
                        mStorePrice2 += mStoreList2.get(i).getGoodsSpecValuesPrice() * mStoreList2.get(i).getCount();
                    }
                }
            }


//       门店优惠金额结算
            settlementStorePrice = mStorePrice - sumStoreDiscount;
            if (settlementStorePrice >= 0) {
                tvGoodsDiscount1.setText("-￥" + String.format("%.2f", tmpStoreGoodsCoupon.getDenomination()));
            } else {
                tvGoodsDiscount1.setText("-￥" + String.format("%.2f", mStorePrice));
            }


        }
        //门店小计=商品+安装费+运费-优惠
        double storeGoodsPrice = 0.00;
        if (settlementStorePrice >= 0) {
            storeGoodsPrice = sumStoreGoodsPrice + sumStoreServicePrice + sumStoreCarriagePrice - sumStoreDiscount;
        } else {
            storeGoodsPrice = sumStoreServicePrice + sumStoreCarriagePrice + mStorePrice2;

        }
        MyLog.e("yang", "storeGoodsPrice==" + storeGoodsPrice + ".....sumStoreGoodsPrice==" + sumStoreGoodsPrice);

        tvGoodsSmallTotal1.setText("￥" + String.format("%.2f", storeGoodsPrice));


//        系统优惠券结算
        List<GoodsEntity> mSystemList = new ArrayList<>();
        List<GoodsEntity> mSystemList2 = new ArrayList<>();
        if (tmpSystemGoodsCoupon != null) {
            for (int i = 0; i < systemList.size(); i++) {
                if (systemList.get(i).getBelongsType().equals("system")) {
                    if (!TextUtils.isEmpty(tmpSystemGoodsCoupon.getGoodsId())) {
                        if (tmpSystemGoodsCoupon.getUseType().equals("all") || tmpSystemGoodsCoupon.getGoodsId().contains(systemList.get(i).getGoodsId() + "")) {
                            mSystemList.add(systemList.get(i));
                            MyLog.e("yang", "MygoodsId====" + systemList.get(i).getGoodsId() + "\n" + i);
                        } else {
                            mSystemList2.add(systemList.get(i));
                        }
                    } else {
                        if (tmpSystemGoodsCoupon.getUseType().equals("all")) {
                            mSystemList.add(systemList.get(i));
                            MyLog.e("yang", "MygoodsId====" + systemList.get(i).getGoodsId() + "\n" + i);
                        } else if (tmpSystemGoodsCoupon.getUseType().equals("only")) {
                            mSystemList.add(systemList.get(i));
                        } else {
                            mSystemList2.add(systemList.get(i));
                        }
                    }


                }

            }


            if (mSystemList != null && mSystemList.size() > 0) {
                for (int i = 0; i < mSystemList.size(); i++) {
                    mSystemPrice += mSystemList.get(i).getGoodsSpecValuesPrice() * mSystemList.get(i).getCount();
                }
            }


            if (mSystemList2 != null && mSystemList2.size() > 0) {
                for (int i = 0; i < mSystemList2.size(); i++) {
                    mSystemPrice2 += mSystemList2.get(i).getGoodsSpecValuesPrice() * mSystemList2.get(i).getCount();
                }
            }

            settlementSystemPrice = mSystemPrice - sumSystemDiscount;

            if (settlementSystemPrice >= 0) {
                tvGoodsDiscount2.setText("-￥" + String.format("%.2f", tmpSystemGoodsCoupon.getDenomination()));
            } else {
                tvGoodsDiscount2.setText("-￥" + String.format("%.2f", mSystemPrice));
            }
        }

        //系统小计=商品+安装费+运费-优惠
        double systemGoodsPrice = 0.00;
        if (settlementSystemPrice >= 0) {
            systemGoodsPrice = sumSystemGoodsPrice + sumSystemServicePrice + sumSystemCarriagePrice - sumSystemDiscount;
        } else {
            systemGoodsPrice = mSystemPrice2 + sumSystemServicePrice + sumSystemCarriagePrice;
        }

        tvGoodsSmallTotal2.setText("￥" + String.format("%.2f", systemGoodsPrice));


        // 转移商品小计
        List<GoodsEntity> mTransferList = new ArrayList<>();
        List<GoodsEntity> mTransferList2 = new ArrayList<>();
        if (tmpTransferGoodsCoupon != null) {
            for (int i = 0; i < transfermList.size(); i++) {
                if (transfermList.get(i).getBelongsType().equals("transfer")) {
                    if (!TextUtils.isEmpty(tmpTransferGoodsCoupon.getGoodsId())) {
                        if (tmpTransferGoodsCoupon.getUseType().equals("all") || tmpTransferGoodsCoupon.getGoodsId().contains(transfermList.get(i).getGoodsId() + "")) {
                            mTransferList.add(transfermList.get(i));
                            MyLog.e("yang", "MygoodsId====" + transfermList.get(i).getGoodsId() + "\n" + i);
                        } else {
                            mTransferList2.add(transfermList.get(i));
                        }
                    } else {
                        if (tmpTransferGoodsCoupon.getUseType().equals("all")) {
                            mTransferList.add(transfermList.get(i));
                            MyLog.e("yang", "MygoodsId====" + transfermList.get(i).getGoodsId() + "\n" + i);
                        } else if (tmpTransferGoodsCoupon.getUseType().equals("only")) {
                            mTransferList.add(transfermList.get(i));
                        } else {
                            mTransferList2.add(transfermList.get(i));
                        }
                    }


                }

            }


            if (mTransferList != null && mTransferList.size() > 0) {
                for (int i = 0; i < mTransferList.size(); i++) {
                    mTransferPrice += mTransferList.get(i).getGoodsSpecValuesPrice() * mTransferList.get(i).getCount();
                }
            }


            if (mTransferList2 != null && mTransferList2.size() > 0) {
                for (int i = 0; i < mTransferList2.size(); i++) {
                    mTransferPrice2 += mTransferList2.get(i).getGoodsSpecValuesPrice() * mTransferList2.get(i).getCount();
                }
            }

            settlementTransferPrice = mTransferPrice - sumTransferDiscount;

            if (settlementTransferPrice >= 0) {
                tvGoodsDiscount3.setText("-￥" + String.format("%.2f", tmpTransferGoodsCoupon.getDenomination()));
            } else {
                tvGoodsDiscount3.setText("-￥" + String.format("%.2f", mTransferPrice));
            }
        }


        //转移小计=商品+安装费+运费-优惠
        double transferGoodsPrice = 0.00;
        if (settlementTransferPrice >= 0) {
            transferGoodsPrice = sumTransferGoodsPrice + sumTransferServicePrice + sumTransferCarriagePrice - sumTransferDiscount;
        } else {
            transferGoodsPrice = mTransferPrice2 + sumTransferServicePrice + sumTransferCarriagePrice;
        }

        tvGoodsSmallTotal3.setText("￥" + String.format("%.2f", transferGoodsPrice));


        //总价
        tvPayAmount.setText("￥" + String.format("%.2f", storeGoodsPrice + systemGoodsPrice + transferGoodsPrice));
        if (!hasGetCarriagePrice || tmpUserLocation == null) {
            tvSubmitOrder.setBackgroundColor(Color.parseColor("#CCCCCC"));
        } else {
            tvSubmitOrder.setBackgroundResource(R.color.appThemeColor);
            tvSubmitOrder.setEnabled(true);
        }
    }

    //    计算运费
    private void collectFreight() {
        sumStoreCarriagePrice = 0;
        sumSystemCarriagePrice = 0;
        carriagePriceMap.clear();
        carriagePriceIndex = new ArrayList<>();
        hasGetCarriagePrice = false;
        // 当没有选中任何地址时,取消获取运费
        switch (confirmOrderJumpType) {
            case WORK:
                if (tmpSelectStore == null && tmpUserLocation == null) {
                    calculatePickedGoods();
                    return;
                }
                break;
            case CART:
                if ((needInstall && installStoreAllSame) || UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) {
                    if (tmpSelectStore == null && tmpUserLocation == null) {
                        calculatePickedGoods();
                        return;
                    }
                } else {
                    if (tmpUserLocation == null) {
                        calculatePickedGoods();
                        return;
                    }
                }
                break;
        }
        CollectFreightApi mApi = new CollectFreightApi(new HttpOnNextListener<String[]>() {
            @Override
            public void onNext(String[] o) {
                if (carriagePriceIndex.size() == o.length) {
                    //门店
                    StringBuffer sbStoreGoodsId = new StringBuffer();
                    if (storeList != null && storeList.size() > 0) {
                        for (int m = 0; m < storeList.size(); m++) {
                            sbStoreGoodsId.append(storeList.get(m).getGoodsSpecValuesId() + ",");
                        }
                    }
                    //系统
                    StringBuffer sbSystemGoodsId = new StringBuffer();
                    if (systemList != null && systemList.size() > 0) {
                        for (int m = 0; m < systemList.size(); m++) {
                            sbSystemGoodsId.append(systemList.get(m).getGoodsSpecValuesId() + ",");
                        }
                    }

                    // 转移
                    StringBuffer sbTransferGoodsId = new StringBuffer();
                    if (transfermList != null && transfermList.size() > 0) {
                        for (int m = 0; m < transfermList.size(); m++) {
                            sbTransferGoodsId.append(transfermList.get(m).getGoodsSpecValuesId() + ",");
                        }
                    }

                    MyLog.e("yang", "sbStoreGoodsId==" + sbStoreGoodsId.toString() + "...sbSystemGoodsId==" + sbSystemGoodsId.toString() + "...sbTransferGoodsId==" + sbTransferGoodsId.toString());

                    for (int i = 0; i < o.length; i++) {
                        String[] mapEle = o[i].split(":");
                        if (mapEle.length > 1) {
                            carriagePriceMap.put(carriagePriceIndex.get(i), Double.parseDouble(mapEle[1]));
                            MyLog.e("yang", "key========" + mapEle[0]);
                            MyLog.e("yang", "value=========" + Double.parseDouble(mapEle[1]));

                            if (!TextUtils.isEmpty(sbStoreGoodsId)) {
                                if (sbStoreGoodsId.toString().contains(mapEle[0])) {
                                    sumStoreCarriagePrice += Double.parseDouble(mapEle[1]);
                                }
                            }


                            if (!TextUtils.isEmpty(sbSystemGoodsId)) {
                                if (sbSystemGoodsId.toString().contains(mapEle[0])) {
                                    sumSystemCarriagePrice += Double.parseDouble(mapEle[1]);
                                }
                            }


                            if (!TextUtils.isEmpty(sbTransferGoodsId)) {
                                if (sbTransferGoodsId.toString().contains(mapEle[0])) {
                                    sumTransferCarriagePrice += Double.parseDouble(mapEle[1]);
                                }
                            }
                        }

                    }

                }

                hasGetCarriagePrice = true;
                calculatePickedGoods();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
            }
        }, this);
        String goodsSpecValuesId = "", logisticsTemplateId = "", name = "", provinceId = "", cityId = "", num = "";
        for (int i = 0; i < goodsList.size(); i++) {
            //if(goodsList.get(i).getLogisticsTemplateId() != 0)

            if (goodsList.get(i).getDeliveryWay() != null && goodsList.get(i).getDeliveryWay().getDeliveryWayId() > 0) {
                carriagePriceIndex.add(i);
                name += (TextUtils.isEmpty(name) ? "" : ",") + goodsList.get(i).getDeliveryWay().getName();

                goodsSpecValuesId += (TextUtils.isEmpty(goodsSpecValuesId) ? "" : ",") + goodsList.get(i).getGoodsSpecValuesId();
                logisticsTemplateId += (TextUtils.isEmpty(logisticsTemplateId) ? "" : ",") + goodsList.get(i).getLogisticsTemplateId();
                if (tmpUserLocation == null) {
                    provinceId += (TextUtils.isEmpty(provinceId) ? "" : ",") + "0";
                    cityId += (TextUtils.isEmpty(cityId) ? "" : ",") + "0";
                } else {
                    provinceId += (TextUtils.isEmpty(provinceId) ? "" : ",") + tmpUserLocation.getProvinceId();
                    cityId += (TextUtils.isEmpty(cityId) ? "" : ",") + tmpUserLocation.getCityId();
                }

                num += (TextUtils.isEmpty(num) ? "" : ",") + goodsList.get(i).getCount();
            }
        }
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSession(this));
        requestMap.put("goodsSpecValuesId", goodsSpecValuesId);
        requestMap.put("logisticsTemplateId", logisticsTemplateId);
        requestMap.put("name", name);
        requestMap.put("provinceId", provinceId);
        requestMap.put("cityId", cityId);
        requestMap.put("num", num);
        MyLog.e("yang", "requestMap==" + requestMap.toString());
        if (((needInstall && installStoreAllSame) || UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) && tmpSelectStore != null) {
            requestMap.put("storeId", "" + tmpSelectStore.getStoreId());
        } else {
            requestMap.put("storeId", "0");
        }


        mApi.setMap(requestMap);
        if (TextUtils.isEmpty(name)) {
            hasGetCarriagePrice = true;
            calculatePickedGoods();
        } else {
            HttpManager.getInstance().doHttpDeal(mApi);
        }
    }

    //获取用户地址
    private void getUserAddress() {
        UserLocationApi userLocationApi = new UserLocationApi(new HttpOnNextListener<UserLocationModel>() {
            @Override
            public void onNext(UserLocationModel model) {
                showAddress(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<UserLocationModel>>() {
                }.getType();
                BaseResultEntity<UserLocationModel> cacheList = gson.fromJson(cache, type);
                showAddress(cacheList.getData());

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                tvHomeDeliveryNone.setVisibility(View.VISIBLE);
                rlHomeDeliveryContent.setVisibility(View.GONE);

                tvStoreDeliveryNone.setVisibility(View.VISIBLE);
                tvStoreDeliveryName.setVisibility(View.GONE);
                tvStoreDeliveryTelephone.setVisibility(View.GONE);
            }
        }, ConfirmOrderActivity.this);
        userLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(ConfirmOrderActivity.this).getSession());
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(userLocationApi);
    }

    //提交订单
    private void submitOrder() {
        tvSubmitOrder.setEnabled(false);
        SubmitOrderApi mApi = new SubmitOrderApi(new HttpOnNextListener<List<CommitOrderModel>>() {
            @Override
            public void onNext(List<CommitOrderModel> list) {
                double total = 0.00;
                int storeId = 0;
                String orderType = "", orderNumber = "", shippingAddressName, shippingAddressContact, shippingAddress;
                for (int i = 0; i < list.size(); i++) {
                    orderType += list.get(i).getOrderType() + ",";
                    total += list.get(i).getTotal();
                    orderNumber += list.get(i).getOrderNumber() + ",";
                    if (list.get(i).getOrderType().equals("store")) {
                        storeId = list.get(i).getStoreId();
                    }
                }
                if (total == 0) {
                    Intent ti = new Intent(ConfirmOrderActivity.this, OrderActivity.class);
                    ti.putExtra("currentId", 0);
                    startActivity(ti);
                } else {
                    shippingAddressName = list.get(0).getShippingAddressName();
                    shippingAddressContact = list.get(0).getShippingAddressContact();
                    shippingAddress = list.get(0).getShippingAddress();
                    Intent ti = new Intent(ConfirmOrderActivity.this, OrderPaidActivity.class);
                    ti.putExtra("totalPrice", total);
                    ti.putExtra("orderNumber", orderNumber.substring(0, orderNumber.length() - 1));
                    ti.putExtra("name", shippingAddressName);
                    ti.putExtra("contact", shippingAddressContact);
                    ti.putExtra("address", shippingAddress);
                    ti.putExtra("storeId", storeId);
                    ti.putExtra("orderType", orderType.substring(0, orderType.length() - 1));
                    setResult(RESULT_OK);
                    startActivity(ti);
                }

                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Toast.makeText(ConfirmOrderActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                tvSubmitOrder.setEnabled(true);
            }
        }, this);
        String freight = "", goodsId = "", numbers = "", specGroupKeys = "", needService = "", storeId = "", deliveryWayId = "", shopCarId = "";
        for (int i = 0; i < goodsList.size(); i++) {
            if (carriagePriceMap.containsKey(i)) {
                freight += (i == 0 ? "" : ",") + carriagePriceMap.get(i);
            } else {
                freight += (i == 0 ? "0" : ",0");
            }
            goodsId += (i == 0 ? "" : ",") + goodsList.get(i).getGoodsId();
            numbers += (i == 0 ? "" : ",") + goodsList.get(i).getCount();
            specGroupKeys += (i == 0 ? "" : ",") + goodsList.get(i).getSpecGroupKey();
            needService += (i == 0 ? "" : ",") + (confirmOrderJumpType != ConfirmOrderJumpType.WORK && goodsList.get(i).isNeedInstall());
            switch (confirmOrderJumpType) {
                case WORK:
                    if (tmpSelectStore == null) {
                        storeId += (i == 0 ? "0" : ",0");
                    } else {
                        storeId += (i == 0 ? "" : ",") + tmpSelectStore.getStoreId();
                    }
                    break;
                case CART:
                    storeId += (i == 0 ? "" : ",") + goodsList.get(i).getServiceInstallStoreId();
                    break;
            }


            if (goodsList.get(i).getDeliveryWay() == null || goodsList.get(i).getDeliveryWay().getDeliveryWayId() == 0 || goodsList.get(i).getLogisticsTemplateId() == 0) {
                deliveryWayId += (i == 0 ? "0" : ",0");
            } else {
                deliveryWayId += (i == 0 ? "" : ",") + goodsList.get(i).getDeliveryWay().getDeliveryWayId();
            }
            shopCarId += (i == 0 ? "" : ",") + goodsList.get(i).getShoppingCartId();
        }
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        if (etGoodsNote != null) {
            requestMap.put("note", etGoodsNote.getText().toString().trim());
        }
        requestMap.put("shipAddressId", tmpUserLocation.getUserLocationId());
        requestMap.put("freight", "" + freight);
        requestMap.put("goodsId", "" + goodsId);
        requestMap.put("numbers", "" + numbers);
        requestMap.put("specGroupKeys", "" + specGroupKeys);
        requestMap.put("needService", "" + needService);
        requestMap.put("storeId", "" + storeId);
        requestMap.put("deliveryWayId", "" + deliveryWayId);
        if (!isSecKill) {
            requestMap.put("isShopCar", "" + (confirmOrderJumpType == ConfirmOrderJumpType.WORK ? 1 : 2));
        }

        if (receiveStoreId != 0) {
            requestMap.put("receiveStoreId", receiveStoreId + "");
        }

        if (tmpSelectStore != null) {
            requestMap.put("storeAddress", "" + tmpSelectStore.getStoreLocation());
        }

//        storeCouponsId ,systemCouponsId,transferCouponsId
        if (tmpStoreGoodsCoupon != null) {
            requestMap.put("storeCouponsId", "" + tmpStoreGoodsCoupon.getCouponsId());
        }

        if (tmpSystemGoodsCoupon != null) {
            requestMap.put("systemCouponsId", "" + tmpSystemGoodsCoupon.getCouponsId());
        }
        if (tmpTransferGoodsCoupon != null) {
            requestMap.put("transferCouponsId", "" + tmpTransferGoodsCoupon.getCouponsId());
        }
        if (confirmOrderJumpType == ConfirmOrderJumpType.WORK) {
            if (mCarInfo == null) {
                Toast.makeText(this, "车辆信息有误,无法提交订单!", Toast.LENGTH_SHORT).show();
                return;
            }
            requestMap.put("ownerCarId", "" + mCarInfo.getOwnerCarId());
        }
        requestMap.put("shopCarId", "" + shopCarId);
        requestMap.put("orderSource", new Gson().toJson(orderSourceEntityList));
        mApi.setMap(requestMap);
        MyLog.e("yang", "requestMap==" + requestMap.toString());
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    //定位初始化控件配置

    /**
     * 获取用户坐标
     */
    private void initLoc() {
        mLoadView.ShowLoadView("定位中..");
        locationClient = new AMapLocationClient(ConfirmOrderActivity.this);
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }

    /**
     * 展示用户收货地址
     *
     * @param model 收货地址
     */
    private void showAddress(UserLocationModel model) {
        if (model.getUserLocationList().size() == 0) {
            tvHomeDeliveryNone.setVisibility(View.VISIBLE);
            rlHomeDeliveryContent.setVisibility(View.GONE);

            tvStoreDeliveryNone.setVisibility(View.VISIBLE);
            tvStoreDeliveryName.setVisibility(View.GONE);
            tvStoreDeliveryTelephone.setVisibility(View.GONE);
        } else {
            tvHomeDeliveryNone.setVisibility(View.GONE);
            rlHomeDeliveryContent.setVisibility(View.VISIBLE);

            tvStoreDeliveryNone.setVisibility(View.GONE);
            tvStoreDeliveryName.setVisibility(View.VISIBLE);
            tvStoreDeliveryTelephone.setVisibility(View.VISIBLE);
            tmpUserLocation = model.getUserLocationList().get(0);
            for (int i = 0; i < model.getUserLocationList().size(); i++) {
                if ("true".equals(model.getUserLocationList().get(i).getIsDefault())) {
                    tmpUserLocation = model.getUserLocationList().get(i);
                    break;
                }
            }

            tvHomeDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
            tvHomeDeliveryTelephone.setText(tmpUserLocation.getContact());
            tvHomeDeliveryAddress.setText(tmpUserLocation.getDetailLocation());

            tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
            tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());
        }
        collectFreight();
    }

    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    longItude = amapLocation.getLongitude();//获取经度
                    latItude = amapLocation.getLatitude();//获取纬度
                    amapLocation.getAccuracy();//获取精度信息

                    if (isFirstLoc) {
                        isFirstLoc = false;
                        locationClient.stopLocation();
                        mLoadView.CancleLoadView();
                        getStoreList(longItude, latItude);
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    locationClient.stopLocation();
                    mLoadView.CancleLoadView();

                    getUserAddress();
                    Log.e("qwe", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    /**
     * 通过地位坐标及商品ID 获取可配送门店
     *
     * @param longItude
     * @param latItude
     */
    private void getStoreList(double longItude, double latItude) {

        SelectStoreApi selectStoreApi = new SelectStoreApi(new HttpOnNextListener<List<SelectStoreModel>>() {
            @Override
            public void onNext(List<SelectStoreModel> list) {
                if (list.size() > 0) {
                    tmpSelectStore = list.get(0);
                    for (int i = 0; i < list.size(); i++) {
                        if (tmpGoodsEntity != null && list.get(i).getStoreId() == tmpGoodsEntity.getServiceInstallStoreId()) {
                            tmpSelectStore = list.get(i);
                            break;
                        }
                    }
                    rlHomeDeliveryWrapper.setVisibility(View.GONE);
                    llStoreDeliveryWrapper.setVisibility(View.VISIBLE);
                    tvStoreDeliveryAddress.setText("配送至" + tmpSelectStore.getStoreName());
                    receiveStoreId = tmpSelectStore.getStoreId();
                    MyLog.e("yang", "默认到店=====" + receiveStoreId);
                    if (tmpSelectStore.getMin() == 0) {
                        tvStoreDeliveryDistance.setText("");
                    } else {
                        tvStoreDeliveryDistance.setText(tmpSelectStore.getMin() + "km");
                    }
                } else {
                    rlHomeDeliveryWrapper.setVisibility(View.VISIBLE);
                    llStoreDeliveryWrapper.setVisibility(View.GONE);
                }
                getUserAddress();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(ConfirmOrderActivity.this, e.getMessage());
            }

        }, ConfirmOrderActivity.this);
        selectStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(ConfirmOrderActivity.this).getSession());
        selectStoreApi.setGprsX(String.valueOf(longItude));
        selectStoreApi.setGprsY(String.valueOf(latItude));
        selectStoreApi.setPage("1");
        selectStoreApi.setSize("10");
        selectStoreApi.setGoodsId("" + installGoodIds);
        if (confirmOrderJumpType == ConfirmOrderJumpType.WORK) {
            selectStoreApi.setType("manual");
        }
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(selectStoreApi);
    }

    //    获取用户优惠券
    private void getUserCoupons() {
        String goodsIds = "";
        /**
         * TODO 根据商品的来源 判断可用优惠券数据
         * */
        GetUserOrderCouponsApi mApi = new GetUserOrderCouponsApi(new HttpOnNextListener<UserOrderCoupon>() {
            @Override
            public void onNext(final UserOrderCoupon o) {
                sumStoreEnabledCoupon = 0;
                sumSystemEnabledCoupon = 0;

                //系统优惠券
                if (o.getSystemList() != null && o.getSystemList().size() > 0) {
                    for (int i = 0; i < o.getSystemList().size(); i++) {
                        if (o.getSystemList().get(i).getMinimum() <= sumSystemGoodsPrice && "normal".equals(o.getSystemList().get(i).getStatus()) && (o.getSystemList().get(i).getEndTime() == 0 || o.getSystemList().get(i).getEndTime() > System.currentTimeMillis())) {
                            if (o.getSystemList().get(i).getUseType().equals("only")) {
                                String couponsGoodsId = o.getSystemList().get(i).getGoodsId();
                                if (TextUtils.isEmpty(couponsGoodsId)) {
                                    sumSystemEnabledCoupon++;
                                } else {
                                    MyLog.e("yang", "installGoodIds==" + installGoodIds);
                                    String[] split = couponsGoodsId.split(",");
                                    for (int m = 0; m < split.length; m++) {
                                        String mGoodsId = split[m];
                                        if (installGoodIds.contains(mGoodsId)) {
                                            MyLog.e("yang", "111111111111111111111");
                                            double mPrice = 0.00;
                                            for (int j = 0; j < systemList.size(); j++) {
                                                if (systemList.get(j).getGoodsId() == Long.valueOf(mGoodsId)) {
                                                    mPrice += systemList.get(j).getGoodsSpecValuesPrice() * systemList.get(j).getCount();
                                                }

                                            }
                                            MyLog.e("yang", "-----------------" + o.getSystemList().get(i).getMinimum() + "\nmPrice==" + mPrice);
                                            if (o.getSystemList().get(i).getMinimum() <= mPrice) {
                                                sumSystemEnabledCoupon++;
                                            }

                                        }
                                    }
                                }

                            } else {
                                sumSystemEnabledCoupon++;
                            }

                        }
                    }
                }
                //优惠券限制使用，当门店零售价— 优惠券金额<门店进价时，买此商品，优惠券不显示！，当门店零售价-优惠券>门店进价，才显示优惠券！
                //转移优惠券
                if (o.getTransferList() != null && o.getTransferList().size() > 0) {
                    for (int i = 0; i < o.getTransferList().size(); i++) {
                        MyLog.e("yang", "零售价==" + sumTransferGoodsPrice);//
                        MyLog.e("yang", "门店价==" + toTransferStorePrice);
                        MyLog.e("yang", "优惠券面额==" + o.getTransferList().get(i).getDenomination());
                        MyLog.e("yang", "优惠券最小面额==" + o.getTransferList().get(i).getMinimum());
                        if ((sumTransferGoodsPrice - o.getTransferList().get(i).getDenomination() >= toTransferStorePrice) && o.getTransferList().get(i).getMinimum() <= sumTransferGoodsPrice && "normal".equals(o.getTransferList().get(i).getStatus()) && (o.getTransferList().get(i).getEndTime() == 0 || o.getTransferList().get(i).getEndTime() > System.currentTimeMillis())) {
                            if (o.getTransferList().get(i).getUseType().equals("only")) {
                                String couponsGoodsId = o.getTransferList().get(i).getGoodsId();
                                if (TextUtils.isEmpty(couponsGoodsId)) {
                                    sumTransferEnabledCoupon++;
                                } else {
                                    MyLog.e("yang", "installGoodIds==" + installGoodIds);
                                    String[] split = couponsGoodsId.split(",");
                                    for (int m = 0; m < split.length; m++) {
                                        String mGoodsId = split[m];
                                        if (installGoodIds.contains(mGoodsId)) {
                                            double mPrice = 0.00;
                                            for (int j = 0; j < transfermList.size(); j++) {
                                                if (transfermList.get(j).getGoodsId() == Long.valueOf(mGoodsId)) {
                                                    mPrice += transfermList.get(j).getGoodsSpecValuesPrice() * transfermList.get(j).getCount();
                                                }

                                            }
                                            MyLog.e("yang", "-----------------" + o.getTransferList().get(i).getMinimum() + "\nmPrice==" + mPrice);
                                            if (o.getTransferList().get(i).getMinimum() <= mPrice) {
                                                sumTransferEnabledCoupon++;
                                            }

                                        }
                                    }
                                }

                            } else {
                                sumTransferEnabledCoupon++;
                            }

                        }
                    }
                }


// 门店优惠券
                if (o.getStoreList() != null && o.getStoreList().size() > 0) {
                    for (int i = 0; i < o.getStoreList().size(); i++) {
                        if (o.getStoreList().get(i).getMinimum() <= sumStoreGoodsPrice && "normal".equals(o.getStoreList().get(i).getStatus()) && (o.getStoreList().get(i).getEndTime() == 0 || o.getStoreList().get(i).getEndTime() > System.currentTimeMillis())) {
                            if (o.getStoreList().get(i).getUseType().equals("only")) {
                                String couponsGoodsId = o.getStoreList().get(i).getGoodsId();
                                if (TextUtils.isEmpty(couponsGoodsId)) {
                                    sumStoreEnabledCoupon++;
                                } else {
                                    MyLog.e("yang", "installGoodIds==" + installGoodIds);
                                    MyLog.e("yang", "*************" + o.getStoreList().get(i).getGoodsId());
                                    String[] split = couponsGoodsId.split(",");
                                    for (int m = 0; m < split.length; m++) {
                                        String mGoodsId = split[m];
                                        if (installGoodIds.contains(mGoodsId)) {
                                            MyLog.e("yang", "111111111111111111111");
                                            double mPrice = 0.00;
                                            for (int j = 0; j < storeList.size(); j++) {
                                                if (storeList.get(j).getGoodsId() == Long.valueOf(mGoodsId)) {
                                                    mPrice += storeList.get(j).getGoodsSpecValuesPrice() * storeList.get(j).getCount();
                                                }

                                            }
                                            if (o.getStoreList().get(i).getMinimum() <= mPrice) {
                                                sumStoreEnabledCoupon++;
                                            }

                                        }
                                    }
                                }

                            } else {
                                sumStoreEnabledCoupon++;
                            }
                        }
                    }
                }


                if (sumStoreEnabledCoupon == 0) {
                    tvCoupon1.setHint("无可用优惠券");
                } else {
                    tvCoupon1.setText("有" + sumStoreEnabledCoupon + "张优惠券");
                    tvCoupon1.setTextColor(ContextCompat.getColor(ConfirmOrderActivity.this, R.color.appThemeColor));

                }

                if (sumSystemEnabledCoupon == 0) {
                    tvCoupon2.setHint("无可用优惠券");
                } else {
                    tvCoupon2.setText("有" + sumSystemEnabledCoupon + "张优惠券");
                    tvCoupon2.setTextColor(ContextCompat.getColor(ConfirmOrderActivity.this, R.color.appThemeColor));
                }

                if (sumTransferEnabledCoupon == 0) {
                    tvCoupon3.setHint("无可用优惠券");
                } else {
                    tvCoupon3.setText("有" + sumTransferEnabledCoupon + "张优惠券");
                    tvCoupon3.setTextColor(ContextCompat.getColor(ConfirmOrderActivity.this, R.color.appThemeColor));
                }


                tvCoupon1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (sumStoreEnabledCoupon == 0) {
                            PhoneUtils.ShowToastMessage(ConfirmOrderActivity.this, "无可用优惠券!");
                        } else {
                            Intent ti = new Intent(ConfirmOrderActivity.this, PickGoodsCouponActivity.class);
                            ti.putExtra(Constants.TRANSMISSION_CONTENT_KEY, (Serializable) o.getStoreList());
                            ti.putExtra("goodCoupon", tmpStoreGoodsCoupon);
                            ti.putExtra("goodPrice", sumStoreGoodsPrice);
                            ti.putExtra("installGoodIds", installGoodIds);
                            ti.putExtra("mList", (Serializable) storeList);
                            startActivityForResult(ti, PICK_COUPON);
                        }
                    }
                });


                tvCoupon2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (sumSystemEnabledCoupon == 0) {
                            PhoneUtils.ShowToastMessage(ConfirmOrderActivity.this, "无可用优惠券!");
                        } else {
                            Intent ti = new Intent(ConfirmOrderActivity.this, PickGoodsCouponActivity.class);
                            ti.putExtra(Constants.TRANSMISSION_CONTENT_KEY, (Serializable) o.getSystemList());
                            ti.putExtra("goodCoupon", tmpSystemGoodsCoupon);
                            ti.putExtra("goodPrice", sumSystemGoodsPrice);
                            ti.putExtra("installGoodIds", installGoodIds);
                            ti.putExtra("mList", (Serializable) systemList);
                            startActivityForResult(ti, PICK_COUPON2);
                        }
                    }
                });

                tvCoupon3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (sumTransferEnabledCoupon == 0) {
                            PhoneUtils.ShowToastMessage(ConfirmOrderActivity.this, "无可用优惠券!");
                        } else {
                            Intent ti = new Intent(ConfirmOrderActivity.this, PickGoodsCouponActivity.class);
                            ti.putExtra(Constants.TRANSMISSION_CONTENT_KEY, (Serializable) o.getTransferList());
                            ti.putExtra("isTransfer", true);
                            ti.putExtra("goodCoupon", tmpTransferGoodsCoupon);
                            ti.putExtra("goodPrice", (sumTransferGoodsPrice - toTransferStorePrice));
                            ti.putExtra("price", sumTransferGoodsPrice);
                            ti.putExtra("installGoodIds", installGoodIds);
                            ti.putExtra("mList", (Serializable) transfermList);
                            startActivityForResult(ti, PICK_COUPON3);
                        }
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
            }
        }, this);
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("session", UserHelper.getInstance().getSession(this));
        requestMap.put("storeId", SharedPreferencesUtils.getParam(ConfirmOrderActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        if (storeList != null && storeList.size() > 0) {
            for (int i = 0; i < storeList.size(); i++) {
                goodsIds += (TextUtils.isEmpty(goodsIds) ? "" : ",") + storeList.get(i).getGoodsId();
            }
        }

        if (systemList != null && systemList.size() > 0) {
            for (int i = 0; i < systemList.size(); i++) {
                goodsIds += (TextUtils.isEmpty(goodsIds) ? "" : ",") + systemList.get(i).getGoodsId();
            }
        }
        if (transfermList != null && transfermList.size() > 0) {
            for (int i = 0; i < transfermList.size(); i++) {
                goodsIds += (TextUtils.isEmpty(goodsIds) ? "" : ",") + transfermList.get(i).getGoodsId();
            }
        }
        if (TextUtils.isEmpty(goodsIds)) {
            requestMap.put("goodsIds", "-1");
        } else {
            requestMap.put("goodsIds", goodsIds);
        }
        mApi.setMap(requestMap);
        MyLog.e("yang", "requestMap==" + requestMap);
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            int backType = data.getIntExtra("backType", 1);
            switch (requestCode) {
                case ADD_ADDRESS:
                    tmpUserLocation = (UserLocationModel.ListBean) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                    tvHomeDeliveryNone.setVisibility(View.GONE);
                    rlHomeDeliveryContent.setVisibility(View.VISIBLE);
                    tvHomeDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                    tvHomeDeliveryTelephone.setText(tmpUserLocation.getContact());
                    tvHomeDeliveryAddress.setText(tmpUserLocation.getDetailLocation());

                    tvStoreDeliveryNone.setVisibility(View.GONE);
                    tvStoreDeliveryName.setVisibility(View.VISIBLE);
                    tvStoreDeliveryTelephone.setVisibility(View.VISIBLE);
                    tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                    tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());

                    collectFreight();
                    break;
                case PICK_ADDRESS_HOME:
                    switch (backType) {
                        case 0:
                            tmpSelectStore = (SelectStoreModel) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                            rlHomeDeliveryWrapper.setVisibility(View.GONE);
                            llStoreDeliveryWrapper.setVisibility(View.VISIBLE);
                            receiveStoreId = tmpSelectStore.getStoreId();
                            MyLog.e("yang", "**********************receiveStoreId===" + receiveStoreId);
                            tvStoreDeliveryAddress.setText("配送至" + tmpSelectStore.getStoreName());
                            if (tmpSelectStore.getMin() == 0) {
                                tvStoreDeliveryDistance.setText("");
                            } else {
                                tvStoreDeliveryDistance.setText(tmpSelectStore.getMin() + "km");
                            }

                            if (tmpUserLocation == null) {
                                getUserAddress();
                            } else {
                                tvStoreDeliveryNone.setVisibility(View.GONE);
                                tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                                tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());
                                collectFreight();
                            }
                            break;
                        case 1:
                            MyLog.e("yang", "配送到家");
                            receiveStoreId = 0;
                            MyLog.e("yang", "到家receiveStoreId==0");
                            tmpUserLocation = (UserLocationModel.ListBean) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                            tvHomeDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                            tvHomeDeliveryTelephone.setText(tmpUserLocation.getContact());
                            tvHomeDeliveryAddress.setText(tmpUserLocation.getDetailLocation());

                            tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                            tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());

                            collectFreight();
                            break;
                    }
                    break;
                case PICK_ADDRESS_STORE:
                    switch (backType) {
                        case 0:
                            tmpSelectStore = (SelectStoreModel) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                            tvStoreDeliveryAddress.setText("配送至" + tmpSelectStore.getStoreName());
                            if (tmpSelectStore.getMin() == 0) {
                                tvStoreDeliveryDistance.setText("");
                            } else {
                                tvStoreDeliveryDistance.setText(tmpSelectStore.getMin() + "km");
                            }
                            receiveStoreId = tmpSelectStore.getStoreId();
                            MyLog.e("yang", "到店====" + receiveStoreId);
                            if (tmpUserLocation == null) {
                                getUserAddress();
                            } else {
                                tvStoreDeliveryNone.setVisibility(View.GONE);
                                tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                                tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());
                                collectFreight();
                            }

                            break;
                        case 1:

                            tmpSelectStore = null;
                            rlHomeDeliveryWrapper.setVisibility(View.VISIBLE);
                            llStoreDeliveryWrapper.setVisibility(View.GONE);
                            tmpUserLocation = (UserLocationModel.ListBean) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                            receiveStoreId = 0;
                            MyLog.e("yang", "到家receiveStoreId==0");
                            tvHomeDeliveryNone.setVisibility(View.GONE);
                            rlHomeDeliveryContent.setVisibility(View.VISIBLE);
                            tvHomeDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                            tvHomeDeliveryTelephone.setText(tmpUserLocation.getContact());
                            tvHomeDeliveryAddress.setText(tmpUserLocation.getDetailLocation());

                            tvStoreDeliveryNone.setVisibility(View.GONE);
                            tvStoreDeliveryName.setVisibility(View.VISIBLE);
                            tvStoreDeliveryTelephone.setVisibility(View.VISIBLE);
                            tvStoreDeliveryName.setText("收货人: " + tmpUserLocation.getContactUser());
                            tvStoreDeliveryTelephone.setText(tmpUserLocation.getContact());
                            collectFreight();
                            break;
                    }
                    break;
                case PICK_COUPON:
                    tmpStoreGoodsCoupon = (GoodsCouponEntity) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                    if (tmpStoreGoodsCoupon == null) {
                        sumStoreDiscount = 0;
                        tvCoupon1.setText("有" + sumStoreEnabledCoupon + "张优惠券");
                        tvGoodsDiscount1.setText("-￥0.00");
                    } else {
                        sumStoreDiscount = tmpStoreGoodsCoupon.getDenomination();
                        tvCoupon1.setText("满" + String.format("%.2f", tmpStoreGoodsCoupon.getMinimum()) + "元减" + String.format("%.2f", tmpStoreGoodsCoupon.getDenomination()) + "元");
                        MyLog.e("yang", "tmpStoreGoodsCoupon====" + tmpStoreGoodsCoupon.getCouponsId());
                    }
                    calculatePickedGoods();
                    break;
                case PICK_COUPON2:
                    tmpSystemGoodsCoupon = (GoodsCouponEntity) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                    if (tmpSystemGoodsCoupon == null) {
                        sumSystemDiscount = 0;
                        tvCoupon2.setText("有" + sumSystemEnabledCoupon + "张优惠券");
                        tvGoodsDiscount2.setText("-￥0.00");
                    } else {
                        sumSystemDiscount = tmpSystemGoodsCoupon.getDenomination();
                        tvCoupon2.setText("满" + String.format("%.2f", tmpSystemGoodsCoupon.getMinimum()) + "元减" + String.format("%.2f", tmpSystemGoodsCoupon.getDenomination()) + "元");
                        MyLog.e("yang", "tmpSystemGoodsCoupon====" + tmpSystemGoodsCoupon.getCouponsId());
                    }
                    calculatePickedGoods();
                    break;
                case PICK_COUPON3:
                    tmpTransferGoodsCoupon = (GoodsCouponEntity) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                    if (tmpTransferGoodsCoupon == null) {
                        sumTransferDiscount = 0;
                        tvCoupon3.setText("有" + sumTransferEnabledCoupon + "张优惠券");
                        tvGoodsDiscount3.setText("-￥0.00");
                    } else {
                        sumTransferDiscount = tmpTransferGoodsCoupon.getDenomination();
                        tvCoupon3.setText("满" + String.format("%.2f", tmpTransferGoodsCoupon.getMinimum()) + "元减" + String.format("%.2f", tmpTransferGoodsCoupon.getDenomination()) + "元");
                        MyLog.e("yang", "tmpTransferGoodsCoupon====" + tmpTransferGoodsCoupon.getCouponsId());
                    }
                    calculatePickedGoods();
                    break;
            }

        }
    }

    //  2017-9-22 wangyang 收货逻辑修改
    @OnClick({R.id.tv_home_delivery_none, R.id.rl_home_delivery_content, R.id.tv_store_delivery_none,
            R.id.tv_store_delivery_name, R.id.tv_store_delivery_telephone, R.id.rl_store_delivery_address_wrapper,
            R.id.iv_home_delivery_enter})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_home_delivery_none:
            case R.id.tv_store_delivery_none:
            case R.id.iv_home_delivery_enter:
                MyLog.e("yang", "111111111111");
                // TODO 新增地址 并返回
                Intent mIntent3 = new Intent(ConfirmOrderActivity.this, AddReceiverAddress.class);
                mIntent3.putExtra("isEdit", false);
                if (!needInstall && UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() == 0) {
                    mIntent3.putExtra("isFrom", false);
                } else {
                    mIntent3.putExtra("isFrom", true);
                }

                startActivityForResult(mIntent3, ADD_ADDRESS);
                break;
            case R.id.tv_store_delivery_name:
            case R.id.tv_store_delivery_telephone:
                MyLog.e("yang", "22222222222");
                // TODO 跳转配送到家 为了选择联系人
                Intent mIntent5 = new Intent(ConfirmOrderActivity.this, DistributionKindActivity.class);
                mIntent5.putExtra("goodsId", "0");
                mIntent5.putExtra("showType", 1);
                mIntent5.putExtra("isShowTabLayout", false);
                startActivityForResult(mIntent5, PICK_ADDRESS_HOME);
                break;
            case R.id.rl_home_delivery_content:
                // TODO 跳转配送到家
                MyLog.e("yang", "3333333333333");
                Intent mIntent2 = new Intent(ConfirmOrderActivity.this, DistributionKindActivity.class);
                if ((needInstall && installStoreAllSame) || UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) {
                    mIntent2.putExtra("goodsId", "" + installGoodIds);
                    mIntent2.putExtra(TRANSMISSION_GOODS_TYPE_KEY, confirmOrderJumpType);
                    mIntent2.putExtra("isInstall", true);
                } else {
                    mIntent2.putExtra("goodsId", "0");
                    mIntent2.putExtra("isInstall", false);
                }
                mIntent2.putExtra("showType", 1);
//                mIntent2.putExtra("isShowTabLayout",false);
                startActivityForResult(mIntent2, PICK_ADDRESS_HOME);
                break;
            case R.id.rl_store_delivery_address_wrapper:
                MyLog.e("yang", "44444444444444");
                // TODO 跳转配送到店
                Intent mIntent6 = new Intent(ConfirmOrderActivity.this, DistributionKindActivity.class);
                if ((needInstall && installStoreAllSame) || UserHelper.getInstance().getOwnerInfoModel(ConfirmOrderActivity.this).getBindStoreId() != 0) {
                    mIntent6.putExtra("goodsId", "" + installGoodIds);
                    mIntent6.putExtra(TRANSMISSION_GOODS_TYPE_KEY, confirmOrderJumpType);
                } else {
                    mIntent6.putExtra("goodsId", "0");
                }
                mIntent6.putExtra("showType", 0);
                startActivityForResult(mIntent6, PICK_ADDRESS_STORE);
                break;
        }
    }

}
